package com.jy.token;

//java-sdk

import cn.hutool.json.JSONObject;
import com.jy.exception.CustomException;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *access_token访问令牌
 * @author Xiexingxie
 * @date 2022/11/15 下午 02:08
 */


@Configuration
public class DetectionToken {
    /**
     * 官网获取的API Key 更新为你的注册
     */
    private static final String AK = "7uqcZxwk9P8y1jMhPpGpQ3IW";
    /**
     * 官网获取的Secret Key 更新为你的注册
     */
    private static final String SK = "npxqL2dwuMWMF9yXHZ3m16ZyBGTWo4b7";

    public static String getToken() {
        try {
            String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
            String accessTokenURL =
                    authHost + "grant_type=client_credentials" + "&client_id=" + AK + "&client_secret=" + SK;
            URL realUrl = new URL(accessTokenURL);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            connection.setRequestMethod("GET");
            BufferedReader in =
                    new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuffer result = new StringBuffer();
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            JSONObject jsonObject = new JSONObject(result.toString());
            String access_token = jsonObject.getStr("access_token");
            return access_token;
        } catch (Exception e) {
            throw new CustomException(20001, e.getMessage());
        }
    }
}
